# -*- coding: utf-8 -*-
"""
Created on Thu Oct 10 19:34:32 2024

@author: Administrator
"""

import os
import csv
import numpy as np
import pandas as pd
 
def get_stock_value(filename,row,column):

  df=pd.read_csv(filename,header=None,sep=',') 
  #print(df.head())
  #print(df.tail())

  df1=df.iloc[0]
  namelist=df1.tolist()
  #print(namelist)
  #print(type(namelist))
  #print(namelist.index('指数名称'))
  #print(namelist.index('收盘点位'))
  #print(namelist.index('PE-TTM(当前值)'))
  #print(namelist.index('PB(当前值)'))

  """
  df2=df.iloc[:,0]
  zhishu=df2.tolist()
  print(zhishu)
  print(type(zhishu))
  print(zhishu.index('="000001"'))
  print(zhishu.index('="000016"'))
  print(zhishu.index('="000300"'))
  print(zhishu.index('="000905"'))
  """
  df2=df.iloc[:,1]
  zhishu=df2.tolist()
  #print(zhishu)
  #print(type(zhishu))
  #print(zhishu.index('上证指数'))
  #print(zhishu.index('上证50'))
  #print(zhishu.index('沪深300'))
  #print(zhishu.index('中证500'))

  columnindex=namelist.index(column)
  rowindex=zhishu.index(row)

  input_str = str(df.iloc[rowindex,columnindex])
  
  if not input_str.startswith('='):
    stock_value = input_str
  else:
    stock_value = float(input_str.lstrip('='))
  
  return stock_value


#filename="D:\\Backup\\Downloads\\指数价值_市值加权_10年_20241011_180751.csv"
filenames=[f for f in os.listdir("D:\\Backup\\Downloads\\") if f.endswith('.csv')]
print(filenames)
print(len(filenames))


columns=['PE-TTM(当前值)']
columns+=['收盘点位']
columns+=['PB(当前值)']


rows=['A股全指']
rows+=['恒生指数']
rows+=['恒生中国企业指数']
rows+=['中证A500']
rows+=['沪深300']
rows+=['上证50']
rows+=['上证指数']
rows+=['中证白酒']
rows+=['恒生互联网科技业指数']
rows+=['中证500']
rows+=['中证1000']
rows+=['深证成指']
rows+=['创业板指']
rows+=['创业板全指']
rows+=['科创50']
rows+=['科创板全指']

from pyecharts.charts import Line
from pyecharts.charts import Kline
from pyecharts import options as opts


index_html_lines = "<div align=center style=\"width:1800px; height:640px; \">\n <br>"

for column in columns:
  for row in rows:
    kdata = []
    xaxis = []
    for filename in filenames:
      filename="D:\\Backup\\Downloads\\"+filename
      stock_value=get_stock_value(filename,row,column) 
      #print(filename +" " + row + " " + column + ": " + str(stock_value))
      quad_value=[str(stock_value)]*4
      kdata.append(quad_value)
      #kdata.append(stock_value)
      xaxis.append(filename[-17:-11])
    #print(kdata)
    print(xaxis)



    # 创建K线图
    #kline = Line()
    kline = Kline(init_opts=opts.InitOpts(width="1800px",height="640px"))
    #kline.add_xaxis(["2022-01-01", "2022-01-02", "2022-01-03", "2022-01-04", "2022-01-05", "2022-01-06"])  # 设置x轴标签
    kline.add_xaxis(xaxis)  # 设置x轴标签
    kline.add_yaxis(column, kdata, itemstyle_opts=opts.ItemStyleOpts(color="#ec0000"))
    #kline.add_yaxis(series_name="指数走势",  y_axis=kdata, markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(type_="average", name="平均值")] ))
    #kline.add_yaxis(series_name="指数走势",  y_axis=kdata, itemstyle_opts=opts.ItemStyleOpts(color="#ec0000"))
  
    # 设置图表样式
    kline.set_global_opts(
      xaxis_opts=opts.AxisOpts(is_scale=True, type_="category"),
      #yaxis_opts=opts.AxisOpts(is_scale=True, splitarea_opts=opts.SplitAreaOpts(is_show=True, areastyle_opts={"color": "#17233d"})),
      yaxis_opts=opts.AxisOpts(is_scale=True),
      datazoom_opts=[opts.DataZoomOpts(pos_bottom="3%", range_start=0, range_end=100)],
    
      toolbox_opts=opts.ToolboxOpts(
      feature={
          "dataZoom": {"yAxisIndex": "none"},
          "restore": {},
          "saveAsImage": {},
      }
    ),
    
      title_opts=opts.TitleOpts(title=row),  # 设置标题
    )

    render_filename="kline_" + column + "_" + row + ".html"
    # 渲染图表
    kline.render(render_filename)
    # generate index.html
    href_line="<a href=./" + render_filename + ">" + row +"</a>\n"
    index_html_lines += href_line
    
  index_html_lines += " <font color=red> @"
  print (column[0:2])
  if column[0:2] == "PB":
    column_show = "PB当前值"
  elif column[0:2] == "PE": 
    column_show = column[0:7].replace("(","!") 
  else:
    column_show = column[0:7]
  index_html_lines += column_show  
  index_html_lines += "</font><br><br>"


index_html_lines += "</div>"
print(index_html_lines)
with open('index.html','w',encoding='utf-8') as file:
  file.write("<br><br><br>"+index_html_lines)



###############################################################
# Add navigator index_html_lines into all generated html files 
###############################################################
for column in columns:
  for row in rows:
    rendered_filename="kline_" + column + "_" + row + ".html" 
    with open(rendered_filename, 'r') as file:
      content = file.read()
    old_string = "</body>"
    new_string = index_html_lines+"</body>"
    new_content = content.replace(old_string, new_string)
    with open(rendered_filename, 'w', encoding='utf-8') as file:
      file.write(new_content)
  
